package com.hdrx.fundhelper.utils;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfToTxt {

        /**
         * 将PDF文件分页解析为txt格式文件
         * @param fileName
         * @throws IOException
         */
        public static void getPdfFileText(String fileName) throws IOException {
            PdfReader reader = new PdfReader(fileName);
            PdfReaderContentParser parser = new PdfReaderContentParser(reader);
            TextExtractionStrategy strategy;
            List<String> pdfTextList = new ArrayList<String>();
            System.out.println("总共有"+reader.getNumberOfPages()+"页");

            for (int i = 0; i < reader.getNumberOfPages(); i++) {
                strategy = parser.processContent(i+1,
                        new SimpleTextExtractionStrategy());
                pdfTextList.add(strategy.getResultantText().toString());
                int pageSize = i+1;
                FileWriter writer;
                try {
                    String filepath ="E:\\test\\txt\\测试第"+pageSize+"页.txt";
                    // 将文本写入文本文件
                    writer = new FileWriter(filepath);
                    writer.write(pdfTextList.get(i));
                    writer.flush();
                } catch (
                        IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public static void main(String[] args) {

            String fileName = "E:\\1\\123.pdf";
            try {
                getPdfFileText(fileName);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


